package engine.util;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.nio.IntBuffer;
import static org.lwjgl.openal.AL10.*;
import org.lwjgl.util.WaveData;

public class SoundUtil
{
    
    //<editor-fold defaultstate="collapsed" desc="Singleton">
    private static SoundUtil singleton;
    
    public static SoundUtil get()
    {
        if (singleton == null)
        {
            singleton = new SoundUtil();
        }
        return singleton;
    }
    //</editor-fold>
    
    private static final String FILE_PATH = "sounds/";
    private static final String FILE_TYPE = ".wav";
    
    
    private SoundUtil()
    {
    }
    
    public WaveData loadSoundWAV(String fileName)
    {
        WaveData wavFile = null;
        try
        {
            wavFile = WaveData.create(
                new BufferedInputStream(
                    new FileInputStream(
                        SoundUtil.FILE_PATH + fileName + SoundUtil.FILE_TYPE
                    )
                )
            );
        }
        catch (FileNotFoundException ex)
        {
            System.out.println(ex);
            System.exit(1);
        }
        return wavFile;
    }
    
    public int genALSoundBuffer(WaveData wavFile)
    {
        IntBuffer bufferID = DataUtil.get().reserveDataInt(1);
        alGenBuffers(bufferID);
        int soundBufferID = bufferID.get(0);
        alBufferData(soundBufferID, wavFile.format, wavFile.data, wavFile.samplerate);
        wavFile.dispose();
        return soundBufferID;
    }
    
    public int genALSoundSource()
    {
        IntBuffer sourceID = DataUtil.get().reserveDataInt(1);
        alGenSources(sourceID);
        int soundSourceID = sourceID.get(0);
        return soundSourceID;
    }
    
}
